<template>
  <div v-if = "isshow">
    categories
  </div>
  <div v-else>
    <self-breadcrumb :bread-arr = "categoriesBread"></self-breadcrumb>
    <el-card class = "box-card">
      <div slot = "header" class = "clearfix">
        <el-button type = "primary" @click = "addCategoriesButton">添加分类</el-button>
      </div>
      <!--
          想在这里渲染树形数据形成树形表，但是在el中的树形表还不够完善，不能达到想要的结果 所以我们需要安装
          可以直接在vue-ui 中直接安装运行依赖 vue-table-with-tree-grid 这个js库来完成
          注册有两种方法
          1. 导入对应的插件 然后使用 Vue.use() 注册  使用这个方法时 导入的插件名称必须为 ZkTable
          2. 导入对应的插件 使用Vue.component() 注册 使用这个方法时 导入的插件名称可以任意设置
          因为这个js库本身就是为了树形表设计的，所以当数据集合中有children属性，它就会渲染出来，并且会自带复选框和展开按钮
      -->
      <!-- data绑定需要使用的数据集合，columns绑定每一列的标题和对应的数据项，columns的规则看data中的columns -->
      <tree-table
        :data = "categoriesList"
        border
        show-index
        :expand-type = "false"
        :selection-type = "false"
        :show-row-hover = "false"
        index-text = "#"
        :columns = "columns">
        <!--
        因为下面定义了type:template 且template:isok 所以这里应该有一个template 且slot=isok,
        并且可以传入scope="scope" 与el-table中的scope类似
        -->
        <template slot = "isok" scope = "scope">
          <i v-if = "!scope.row.cat_deleted" class = "el-icon-success" style = "color:green"> </i>
          <i v-else class = "el-icon-error" style = "color:red"> </i>
        </template>
        <template slot = "sort" scope = "scope">
          <el-tag v-if = "scope.row.cat_level===0" type = "primary">一级</el-tag>
          <el-tag v-else-if = "scope.row.cat_level===1" type = "success">二级</el-tag>
          <el-tag v-else type = "warning">三级</el-tag>
        </template>
        <template slot = "operation" scope = "scope">
          <el-button @click = "editCategoriesButton(scope.row)" size = "small" icon = "el-icon-edit" type = "primary">编辑
          </el-button>
          <el-button @click = "deleteCategoriesButton(scope.row)" size = "small" icon = "el-icon-delete"
                     type = "danger">
            删除
          </el-button>
        </template>
      </tree-table>
      <el-pagination
        background
        layout = "total,sizes,prev, pager, next"
        @current-change = "handleCurrentChange"
        :page-size = "queryCategories.pagesize"
        :current-page = "queryCategories.pagenum"
        :page-sizes = "[2,5,10,50]"
        @size-change = "handleSizeChange"
        :total = "total">
      </el-pagination>
    </el-card>
    <el-dialog
      title = "添加分类"
      :visible.sync = "addCategoriesVisible"
      width = "50%">
      <el-form ref = "addCategoriesFormRef" :rules = "addCategoriesFormRules" :model = "addCategoriesForm"
               label-width = "80px">
        <el-form-item label = "分类名称" prop = "cat_name">
          <el-input v-model = "addCategoriesForm.cat_name"></el-input>
        </el-form-item>
        <el-form-item label = "父级分类" prop = "cat_pid">
          <!--
              这里不应该用el-select，因为这里需要分为两级菜单，只用一个select是不能分为两级的，应该使用Cascader级联选择器
              这里有可能会出现高度错误的问题，我们只需要在全局样式 global.css中添加 .el-cascader-menu{ height: 300px; }
              v-model 就是双向绑定的值  options 是需要使用数据的数组  props是一系列配置传入对象，比如expandTrigger表示
              展开触发的方式hover就是鼠标经过触发展开。 value就相当于input的value用于表单提交的值，  label就是看到的选项
              checkStrictly就是让选择器可以单选一级菜单或二级菜单。  emitPath:只存入选中的value值，而不是一个数组
              change事件就是选择的选项改变后触发该事件
           -->
          <el-cascader
            v-model = "addCategoriesForm.cat_pid"
            :options = "addCategoriesPid"
            placeholder = "不选择，默认为一级分类"
            style = "width: 100%"
            :props = "{expandTrigger:'hover',value:'cat_id',label:'cat_name',checkStrictly: true,emitPath:false }"
            ref = "elCascader"
            @change = "Cchange"
            clearable>
          </el-cascader>
        </el-form-item>
      </el-form>
      <span slot = "footer" class = "dialog-footer">
        <el-button @click = "addCategoriesVisible = false">取 消</el-button>
        <el-button type = "primary" @click = "addCategoriesDefine">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      title = "编辑分类"
      :visible.sync = "editCategoriesVisible"
      width = "50%">
      <el-form ref = "editCategoriesFormRef" :rules = "editCategoriesRules" :model = "editCategoriesForm"
               label-width = "80px">
        <el-form-item prop = "cat_name" label = "分类名称">
          <el-input v-model = "editCategoriesForm.cat_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot = "footer" class = "dialog-footer">
        <el-button @click = "editCategoriesVisible = false">取 消</el-button>
        <el-button type = "primary" @click = "editCategoriesDefine">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import SelfBreadcrumb from '../SelfBreadcrumb'

export default {
  name: 'Categories',
  components: {
    SelfBreadcrumb
  },
  created () {
    this.getCategoriesList()
  },
  data () {
    return {
      addCategoriesVisible: false,
      isshow: false,
      categoriesBread: ['商品管理', '商品分裂'],
      categoriesList: [],
      queryCategories: {
        type: 3,
        pagenum: 1,
        pagesize: 5
      },
      categoriesTreeProp: {},
      columns: [
        {
          label: '分类名称',
          prop: 'cat_name'
        }, {
          // 使用了这个js库中的插槽，与el-table中每一el-column不一样 因为这个js库只有一个标签，每一列都是自动渲染的
          // 所以需要使用具名插槽，
          label: '是否有效',
          // 先使用type:template 说明这个列是自定义内容
          type: 'template',
          // 再使用template:''  定义插槽的名字，这里就使用了具名插槽，自定义插槽的名字
          template: 'isok'
        },
        {
          label: '排序',
          type: 'template',
          template: 'sort'
        },
        {
          label: '操作',
          type: 'template',
          template: 'operation'
        }
      ],
      total: 0,
      editCategories: {},
      addCategoriesForm: {
        cat_name: '',
        cat_pid: 0,
        cat_level: 0
      },
      addCategoriesFormRules: {
        cat_name: [
          { required: true, message: '分类名称不能为空', trigger: 'blur' }
        ],
        cat_pid: [
          { required: true, message: '父级分类不能为空', trigger: 'blur' }
        ]
      },
      addCategoriesPid: [],
      editCategoriesVisible: false,
      editCategoriesId: 0,
      editCategoriesForm: {
        cat_name: ''
      },
      editCategoriesRules: {
        cat_name: [{ required: true, message: '分类名不能为空', trigger: 'blur' }]
      }
    }
  },
  methods: {
    async getCategoriesList () {
      const { data: res } = await this.$http.get('categories', { params: this.queryCategories })
      this.process(res)
      this.categoriesList = res.data.result
      this.total = res.data.total
    },
    process (res) {
      const status = res.meta.status
      const msg = res.meta.msg
      if (status === 200 || status === 201 || status === 204) { this.$message.success(msg) } else {
        this.$message.error(msg)
      }
    },
    handleCurrentChange (val) {
      this.queryCategories.pagenum = val
      this.getCategoriesList()
    },
    handleSizeChange (val) {
      this.queryCategories.pagesize = val
      this.getCategoriesList()
    },
    editCategoriesButton (row) {
      this.editCategoriesVisible = true
      this.editCategoriesId = row.cat_id
      this.editCategoriesForm.cat_name = row.cat_name
    },
    async editCategoriesDefine () {
      this.$refs.editCategoriesFormRef.validate(valid => {
        if (!valid) return
      })
      const { data: res } = await this.$http.put(`categories/${this.editCategoriesId}`, {
        cat_name: this.editCategoriesForm.cat_name
      })
      this.process(res)
      this.getCategoriesList()
      this.editCategoriesVisible = false
    },
    async deleteCategoriesButton (row) {
      const { data: res } = await this.$http.delete(`categories/${row.cat_id}`)
      this.process(res)
    },
    async addCategoriesButton () {
      const { data: res } = await this.$http.get('categories', {
        params: {
          type: 2
        }
      })
      this.addCategoriesPid = res.data
      this.addCategoriesVisible = true
    },
    async addCategoriesDefine () {
      this.$refs.addCategoriesFormRef.validate(valid => {
        if (!valid) return
      })
      const { data: res } = await this.$http.post('categories', this.addCategoriesForm)
      this.process(res)
      this.getCategoriesList()
      this.addCategoriesVisible = false
      this.$refs.addCategoriesFormRef.resetFields()
    },
    Cchange () {
      this.addCategoriesForm.cat_level = this.$refs.elCascader.getCheckedNodes()[0].data.cat_level + 1
      console.log(this.addCategoriesForm)
    }
  }
}
</script>

<style scoped>
  .el-card {
    margin-top: 10px;
  }

  .el-pagination {
    margin-top: 10px;
  }
</style>
